import request from "./request";
import { ElMessage } from "element-plus";
import cache from "@/utils/cache";

const CACHE_KEY = {
  CATEGORY_LIST: "category_list",
  CATEGORY_TREE: "category_tree",
  CATEGORY_DETAIL: "category_detail_",
  CATEGORY_TOP_LIST: "category_top_list",
};

const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

/**
 * 统一的错误处理
 * @param {Error} error - 错误对象
 * @param {string} customMessage - 自定义错误消息
 */
const handleError = (error, customMessage = "操作失败") => {
  console.error(error);
  ElMessage.error(customMessage);
  throw error;
};

/**
 * 获取所有分类
 * @returns {Promise} - 返回分类列表数据
 */
export async function getCategories() {
  try {
    const cacheKey = CACHE_KEY.CATEGORY_LIST;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: "/Category/list",
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取分类列表失败");
  }
}

/**
 * 获取顶级菜单
 * @returns {Promise} - 返回菜单列表数据
 */
export async function getTopCategories() {
  try {
    const cacheTopKey = CACHE_KEY.CATEGORY_TOP_LIST;
    const cachedData = cache.get(cacheTopKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: "/Category/topList",
      method: "get",
    });

    cache.set(cacheTopKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取菜单列表失败");
  }
}
/**
 * 获取分类详情
 * @param {number} id - 分类ID
 * @returns {Promise} - 返回分类详情
 */
export async function getCategory(id) {
  try {
    if (!id) throw new Error("分类ID不能为空");

    const cacheKey = `${CACHE_KEY.CATEGORY_DETAIL}${id}`;
    const cachedData = cache.get(cacheKey);
    if (cachedData) {
      return cachedData;
    }

    const response = await request({
      url: `/Category/detail/${id}`,
      method: "get",
    });

    cache.set(cacheKey, response, CACHE_DURATION);
    return response;
  } catch (error) {
    handleError(error, "获取分类详情失败");
  }
}

/**
 * 创建新分类
 * @param {Object} categoryData - 分类数据
 * @returns {Promise} - 返回创建结果
 */
export const createCategory = async (categoryData) => {
  try {
    if (!categoryData.name) throw new Error("分类名称不能为空");

    const response = await request({
      url: "/Category/create",
      method: "POST",
      data: categoryData,
    });

    // 清除相关缓存
    cache.remove(CACHE_KEY.CATEGORY_LIST);
    cache.remove(CACHE_KEY.CATEGORY_TREE);

    return response;
  } catch (error) {
    handleError(error, "创建分类失败");
  }
};

/**
 * 更新分类信息
 * @param {Object} categoryData - 包含ID的分类数据
 * @returns {Promise} - 返回更新结果
 */
export const updateCategory = async (categoryData) => {
  try {
    if (!categoryData.id) throw new Error("分类ID不能为空");
    if (!categoryData.name) throw new Error("分类名称不能为空");

    const response = await request({
      url: `/Category/update/${categoryData.id}`,
      method: "PUT",
      data: categoryData,
    });

    // 清除相关缓存
    cache.remove(CACHE_KEY.CATEGORY_LIST);
    cache.remove(CACHE_KEY.CATEGORY_TREE);
    cache.remove(`${CACHE_KEY.CATEGORY_DETAIL}${categoryData.id}`);

    return response;
  } catch (error) {
    handleError(error, "更新分类失败");
  }
};

/**
 * 删除分类
 * @param {number} id - 要删除的分类ID
 * @returns {Promise} - 返回删除结果
 */
export const deleteCategory = async (id) => {
  try {
    if (!id) throw new Error("分类ID不能为空");

    const response = await request({
      url: `/Category/delete/${id}`,
      method: "DELETE",
    });

    // 清除相关缓存
    cache.remove(CACHE_KEY.CATEGORY_LIST);
    cache.remove(CACHE_KEY.CATEGORY_TREE);
    cache.remove(`${CACHE_KEY.CATEGORY_DETAIL}${id}`);

    return response;
  } catch (error) {
    handleError(error, "删除分类失败");
  }
};
